package com.dennis.nio;

import io.netty.channel.Channel;
import io.netty.channel.ChannelHandler.Sharable;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;

import java.net.InetSocketAddress;
import java.util.Map;
import java.util.concurrent.atomic.LongAdder;

/**
 * @author Dennis Li
 * @date 2020/8/4 10:46
 */
@Sharable
public class ServerHandler extends ChannelInboundHandlerAdapter {

    private final Map<String, Channel> map = ChannelMap.getInstance();

    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        ctx.writeAndFlush("Server has read this message");
    }

    @Override
    public void handlerAdded(ChannelHandlerContext ctx) throws Exception {
        Channel channel = ctx.channel();
        final String hostName = ((InetSocketAddress) ctx.channel().remoteAddress()).getHostName();
        map.put(hostName, channel);
    }

    @Override
    public void handlerRemoved(ChannelHandlerContext ctx) throws Exception {
        Channel channel = ctx.channel();
        final String hostName = ((InetSocketAddress) channel.remoteAddress()).getHostName();
        map.remove(hostName);
    }

    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) {
        ctx.writeAndFlush("Server has read this message");
    }

}
